package net.atomarrow.db.pool;

import java.sql.Connection;
import java.sql.SQLException;

import net.atomarrow.annotation.Inject;
import net.atomarrow.configs.DbConfig;

public class ConnectionProvider {

	@Inject
	private DbConfig dbConfig;

	public Connection getConection(boolean needTx) {
		try {
			Connection conn = dbConfig.getDataSource().getDataSource().getConnection();
			if (needTx) {
				// conn.setTransactionIsolation()//TODO 可配置
				conn.setAutoCommit(false);
			} else {
				conn.setReadOnly(true);
			}
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void closeConnection(Connection conn) {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.setReadOnly(false);
				if(!conn.getAutoCommit()){
					conn.setAutoCommit(true);
				}
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void commitTx(Connection connection) {
		try {
			if (connection != null) {
				connection.commit();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void rollbackTx(Connection connection) {
		if (connection != null) {
			try {
				connection.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void changeAutoCommitState(Connection connection, boolean needTx) {
		if (connection != null) {
			try {
                connection.setReadOnly(needTx != true);
				connection.setAutoCommit(!needTx);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
